﻿using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Base
{
  public  class FileDAL
    {
        public readonly SqlDbHelper _dbHelper;
        public FileDAL()
        {
            _dbHelper = new SqlDbHelper();
        }


        /// <summary>
        /// 获取附件
        /// </summary>
        /// <param name="recIds">关联主键列表</param>
        /// <returns></returns>
        public IEnumerable<FileModel> GetFiles(List<Guid> recIds)
        {
            string sql = $"select *  from base_file where recid in ('{ string.Join("','", recIds)}')";
            DataTable dt = _dbHelper.executeSqlDataTable(sql);
            var data = _dbHelper.DataTableToList<FileModel>(dt);
            return data;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="insertList"></param>
        public bool SaveFile(List<FileModel> insertList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in insertList)
            {
                string sql = $@"INSERT INTO [dbo].[Base_File]
                                           ([Id]
                                           ,[FileName]
                                           ,[RealName]
                                           ,[FileType]
                                           ,[FilePath]
                                           ,[CreateTime]
                                           ,[CreateUserId]
                                           ,[CreateUserName]
                                           ,[RecId])
                                     VALUES
                                           ('{item.Id }', 
                                            '{item.FileName }', 
                                            '{item.RealName }', 
                                            '{item.FileType }', 
                                            '{item.FilePath }', 
                                            '{item.CreateTime.ToString("yyyy-MM-dd HH:mm:dd") }', 
                                            '{item.CreateUserId }',
                                            '{item.CreateUserName }', 
                                            '{item.RecId }');";
                sb.Append(sql);
            }
            int success = _dbHelper.executeSqlNonQuery(sb.ToString());
            return success > 0;
        }

        /// <summary>
        /// 根据文件的主键去删除
        /// </summary>
        /// <param name="ids">主键的集</param>
        /// <returns></returns>
        public bool Delete(string[] ids)
        {
            string sql = $"delete from Base_File where id in ('{string.Join("','", ids)}');";
            int success = _dbHelper.executeSqlNonQuery(sql);
            return success > 0;
        }
    }
}
